package com.liu.circle;

import java.util.Arrays;

/**
 * @author liucong
 * @date 2021/2/25 - 10:55
 */
public class CircleQueue<E> {
    private int front;
    private int size;
    private Object[] elements;
    private static final int DEFAULT_CAPACITY=10;

    public CircleQueue(){
        elements = new Object[DEFAULT_CAPACITY];
    }

    public int size(){
        return size;
    }

    public boolean isEmpty(){
        return size == 0;
    }

    public void clear(){
        for (int i = 0; i < size; i++) {
            elements[index(i)] = null;
        }
        front = 0;
        size = 0;
    }

    /**
     * 入队
     * @param element
     */
    public void enQueue(E element){
        ensureCapacity(size + 1);
        elements[index(size)] = element;
        size++;
    }

    /**
     * 出队
     * @return
     */
    public E deQueue(){
        rangeCheck();
        Object frontElement = elements[front];
        elements[front] = null;
        front = index(1);
        size--;
        return (E) frontElement;
    }

    /**
     * 队首元素
     * @return
     */
    public E front(){
        return (E) elements[front];
    }

    private void rangeCheck(){
        if(size <= 0){
            throw new IndexOutOfBoundsException("size = "+size);
        }
    }

    /**
     * 确保capacity足够
     * @param capacity
     */
    private void ensureCapacity(int capacity){
        int oldCapacity = elements.length;
        if(capacity<=oldCapacity) return;

        //新容量为旧容量的1.5倍
        int newCapacity = oldCapacity + (oldCapacity >> 1);
        Object[] newElements = new Object[newCapacity];
        for (int i = 0; i < size; i++) {
            newElements[i] = elements[index(i)];
        }
        elements = newElements;
        //重置front
        front = 0;
    }

    /**
     * 获取循环队列的真实索引
     * @param index
     * @return
     */
    private int index(int index){
        //(front + index) % elements.length
        index += front;
        return index - (index >= elements.length ? elements.length : 0);
    }

    @Override
    public String toString() {
        StringBuilder string = new StringBuilder();
        string.append("capacity=").append(elements.length)
                .append(" front=").append(front)
                .append(" size=").append(size).append(", ").append("[");
        for (int i = 0; i < elements.length; i++) {
            if(i!=0)
                string.append(", ");
            string.append(elements[i]);
        }
        string.append("]");
        return string.toString();
    }
}
